package part2.miniTomcat.request;

import lombok.extern.slf4j.Slf4j;
import part2.miniTomcat.Server;

import java.io.*;
import java.nio.charset.StandardCharsets;

/**
 * @author 大忽悠
 * @create 2022/9/1 9:50
 */
@Slf4j
public class Response extends AbstractResponse {
    private static final Integer BUFFER_SIZE=2048;
    private PrintWriter writer;
    private OutputStream out;
    private Request request;

    public Response(OutputStream out) {
        this.out=out;
        writer = new PrintWriter(out, true);
    }

    public void setRequest(Request request) {
      this.request=request;
    }

    public void sendStaticResource() {
        BufferedInputStream inputStream=null;
        String fileName = extractFileNameFromRequest();
        try {
            File file = new File(Server.WEB_ROOT, fileName);
            if(file.exists()){
                log.info("在{}目录下寻找到名为{}的文件,准备响应中...", Server.WEB_ROOT,fileName);
                //写出响应头
                StringBuilder builder=new StringBuilder();
                String string = builder.append("HTTP/1.1 200 OK\r\n")
                        .append("Content-Type:text/html;charset=UTF-8\r\n")
                        .toString();
                writer.println(string);

                //写出文件
                byte[] buffer = new byte[BUFFER_SIZE];
                inputStream= new BufferedInputStream(new FileInputStream(file));
                int count=-1;
                while((count=inputStream.read(buffer))!=-1){
                    out.write(buffer,0,count);
                }
                out.flush();
                }else {
                log.info("没有在{}目录下寻找到名为{}的文件", Server.WEB_ROOT,fileName);
                    fileNotFoundHandle();
                }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if(inputStream!=null){
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    private void fileNotFoundHandle() throws IOException {
        String errorMsg="HTTP/1.1 404 File Not Found \r\n"+
                "Content-Type: text/html\r\n"+
                "Content-Length: 23\r\n"+
                "\r\n"+
                "<h1>File Not Found</h1>";
        out.write(errorMsg.getBytes(StandardCharsets.UTF_8));
    }

    public String extractFileNameFromRequest(){
        return request.getUri().substring(1);
    }

    /**
     * <p>
     *     PrintWriter构造函数第二个参数为true,
     *     表示是否开启自动刷新,传入true表示对println的任何方法都刷新输出,但是print方法不会
     *     当然这个bug后续版本会修改
     * </p>
     * @return
     * @throws IOException
     */
    @Override
    public PrintWriter getWriter() throws IOException {
        return writer;
    }
}
